
// 先创建出 store
const store = {
    getState:()=>{},
    dispatch:(action)=>{
        return action
    },
}

// 中间件1
function func1(store){
    return (next) => {
        return (action) => {
            console.log(1111)
            return next(action)
        }
    }
}

// 中间件2
function func2(store){
    return (next) => {
        return (action) => {
            console.log(2222)
            return next(action)
        }
    }
}

// 中间件3 
function func3(store){
    return (next) => {
        return (action) => {
            console.log(3333)
            return next(action)
        }
    }
}

// 中间件数组
var middlewares = [func1,func2,func3]

const middlewareAPI = {
    getState: store.getState,
    dispatch: (...args) => dispatch(...args)
}
var chain = middlewares.map(item => item(middlewareAPI))


var dispatch = compose(...chain)(store.dispatch)
console.log(dispatch({type:'aaa'}))

function compose(...funcs) {
    if (funcs.length === 0) {
        return arg => arg
    }

    if (funcs.length === 1) {
        return funcs[0]
    }

    return funcs.reduce((acc, cur) => {
        // 累加器 acc 上一次处理的结果，第一次是「初始值」
        // 当前项 cur 当前遍历的数组元素
        return (...args) => {
            return acc(cur(...args))
        }
    })
}
// var  arr = [1, 2, 3, 4];
// var sum = arr.reduce((x,y)=>x+y)
// var mul = arr.reduce((x,y)=>x*y)
// console.log( sum ); //求和，10
// console.log( mul ); //求乘积，24


